/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      add
 * @Description:    JSX文件
 * @Author:         SuPeiSen
 * @CreateDate:     2021/2/25 3:29 下午
 * @UpdateDate:     2021/2/25 3:29 下午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import { IRouteComponentProps } from 'umi';
import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Input, message, Row, Switch } from 'antd';
import {
  AddShareUrlApi,
  GetShareUlrByIdApi,
  UpdateShareUrlApi,
} from '@/service/share_url_api';
import { QiNiuUploadWidget } from '@/widget/qiniu_upload_widget/qiniu_upload_widget';
import { AppConfig, AppImageUrl } from '@/config/app_config';
import { AddAdApi, GetAdByIdApi, UpdateAdApi } from '@/service/ad_api';
import { boolToNumOneOrZero, log, numberToBool } from '@/utils/app_fun';
import { LoadingWidget } from '@/widget/loading_wdiget/loading_widget';

export default (
  props: IRouteComponentProps<
    {},
    {
      id: string;
    }
  >,
) => {
  // 保存广告图片

  const [loading, setLoading] = useState<boolean>(true);
  const adTitleRef = useRef<Input>(null);
  const adUrlRef = useRef<Input>(null);
  const adEmailRef = useRef<Input>(null);
  const pxRef = useRef<Input>(null);
  const remarksRef = useRef(null);
  const statusRef = useRef<{ value: boolean }>({ value: false });
  const adImage = useRef<{ value?: string }>({});

  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  // 使用useForm创建form对象
  const [form] = Form.useForm();

  // get参数
  const queryParam = props.location.query;

  useEffect(() => {
    if (queryParam.id !== undefined) {
      GetAdByIdApi(Number(queryParam.id))
        .then((model) => {
          if (model.success) {
            const adItem = model.data!.data;
            form.setFieldsValue({
              ad_title: adItem.ad_title,
              ad_url: adItem.ad_url,
              ad_email: adItem.ad_email,
              px: adItem.px,
              remarks: adItem.remarks,
            });
            statusRef.current.value = numberToBool(adItem.status);
            adImage.current.value = adItem.ad_image;
            console.log(adImage.current.value);
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, []);

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
  };

  // 提交表单
  const submitInput = (values: any) => {
    setBtnLoading(true);
    if (adImage.current.value !== undefined) {
      if (queryParam.id === undefined) {
        values.ad_image = adImage.current.value;
        AddAdApi(values)
          .then((success) => {
            if (success) {
              message.success('添加成功');
            } else {
              message.error('添加失败');
            }
          })
          .finally(() => {
            setBtnLoading(false);
          });
      } else {
        values.ad_image = adImage.current.value;
        values.status = boolToNumOneOrZero(statusRef.current.value);
        UpdateAdApi(Number(queryParam.id), values)
          .then((success) => {
            if (success) {
              message.success('更新成功');
            } else {
              message.error('更新失败');
            }
          })
          .finally(() => {
            setBtnLoading(false);
          });
      }
    } else {
      message.error('图片不能为空');
    }
  };

  if (queryParam.id === undefined && loading) {
    setLoading(false);
  }
  if (queryParam.id !== undefined && loading) {
    return <LoadingWidget />;
  }

  return (
    <div className="main_div">
      <Row justify="start">
        <Form {...layout} onFinish={submitInput} form={form}>
          {/*链接名称*/}
          <Form.Item
            label="广告标题"
            name="ad_title"
            rules={[
              {
                required: true,
                message: '标题必须',
              },
            ]}
          >
            <Input className="inputLen" ref={adTitleRef} />
          </Form.Item>

          {/*链接地址*/}
          <Form.Item
            label="广告地址"
            name="ad_url"
            rules={[
              {
                required: true,
                message: '地址必须',
              },
            ]}
          >
            <Input className="inputLen" ref={adUrlRef} />
          </Form.Item>

          <Form.Item
            label="广告图片"
            name="ad_image"
            style={{ width: '300px' }}
            valuePropName="fileList"
          >
            {/*Tag对应的图片*/}
            <QiNiuUploadWidget
              onSelect={(url) => {
                adImage.current.value = url;
              }}
              // @ts-ignore
              initValue={
                adImage.current.value === undefined
                  ? []
                  : [
                      {
                        uid: -1,
                        name: adImage.current.value ?? '',
                        status: 'done',
                        type: '',
                        url: AppImageUrl(adImage.current.value),
                        size: 0,
                      },
                    ]
              }
            />
          </Form.Item>

          {/*链接地址*/}
          <Form.Item label="广告邮箱" name="ad_email">
            <Input className="inputLen" ref={adEmailRef} />
          </Form.Item>

          {/*链接排序*/}
          <Form.Item label="排序" name="px">
            <Input className="inputLen" ref={pxRef} />
          </Form.Item>
          {/*备注*/}
          <Form.Item label="备注" name="remarks">
            <Input.TextArea className="inputLen" ref={remarksRef} />
          </Form.Item>

          {/*上架*/}
          <Form.Item
            label="上架"
            valuePropName="checked"
            name="article_status"
            initialValue={statusRef.current.value}
          >
            <Switch onChange={(value) => (statusRef.current.value = value)} />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={btnLoading}
            >
              保存
            </Button>
          </Form.Item>
        </Form>
      </Row>
    </div>
  );
};
